package mshop.com.schild_kotlin.activitys

import android.content.Context
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import kotlinx.android.synthetic.main.activity_search.*
import mshop.com.schild_kotlin.R
import mshop.com.schild_kotlin.base.BaseActivity
import mshop.com.schild_kotlin.fragments.search.HistoryFragment
import mshop.com.schild_kotlin.fragments.search.SearchFragment


/**
 * Created by mayi on 2018/5/28.
 * @Autor CaiWF
 * @Email 401885064@qq.com
 * @TODO
 */
class SearchActivity : BaseActivity(), View.OnClickListener {
    var searchFragment: SearchFragment? = null
    var historyFragment: HistoryFragment? = null

    override fun getLayoutResources(): Int {
        return R.layout.activity_search
    }

    override fun initView() {
        initFragment()
        search_iv.setOnClickListener(this)
        back_iv.setOnClickListener(this)
    }

    private fun initFragment() {
        searchFragment = SearchFragment.getInstall("")
        historyFragment = HistoryFragment.getInstall()

        val fragmentTran = supportFragmentManager.beginTransaction()
        fragmentTran.add(R.id.search_content, searchFragment)
        fragmentTran.add(R.id.search_content, historyFragment)
        fragmentTran.commit()
        fragmentTran.show(historyFragment).hide(searchFragment)
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.back_iv -> finish()
            R.id.search_iv -> {
                var searchKey = search_edit.text.toString()
                if (TextUtils.isEmpty(searchKey)) {
                    toastShow("请输入搜索关键词!")
                    return
                }
                toSearch(searchKey)
            }
        }
    }


    /**
     * 进行搜索
     */
    fun toSearch(searchKey: String) {

        searchFragment?.let {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
            supportFragmentManager
                    .beginTransaction()
                    .show(it)
                    .hide(historyFragment)
                    .commit()
            it.search(searchKey)
        }

        historyFragment?.let {
            it.addHistory(searchKey)
        }
    }

    override fun getNeedRefresh(): Boolean {
        return false
    }

    override fun onRefresh() {
    }

}